<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <!-- 条件搜索 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="订单编码/订单合同号">
                <a-input v-model="queryParam.orderCode" placeholder="请输入" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="客户名">
                <a-input v-model="queryParam.customerName" placeholder="请输入" allow-clear />
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="公司">
                  <a-input v-model="queryParam.company" placeholder="请输入" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="部门">
                  <a-input v-model="queryParam.department" placeholder="请输入" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="接单员">
                  <a-input v-model="queryParam.username" placeholder="请输入" allow-clear />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="状态">
                  <a-select placeholder="请选择状态" style="width: 100%" allow-clear>
                    <a-select-option
                      v-for="(d, index) in orderStatus"
                      :key="index"
                      :value="d.dictValue"
                    >{{ d.dictLabel }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="创建时间">
                  <a-range-picker
                    v-model="createDateRange"
                    valueFormat="YYYY-MM-DD"
                    format="YYYY-MM-DD"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="送货时间">
                  <a-range-picker
                    v-model="deliveryDateRange"
                    valueFormat="YYYY-MM-DD"
                    format="YYYY-MM-DD"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="advanced && { float: 'right', overflow: 'hidden' } || {}"
              >
                <a-button type="primary" @click="handleQuery">
                  <a-icon type="search" />查询
                </a-button>
                <a-button style="margin-left: 8px" @click="resetQuery">
                  <a-icon type="redo" />重置
                </a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- 操作 -->
      <div class="table-operations">
        <a-button type="primary" @click="$refs.createForm.handleAdd()">
          <a-icon type="plus" />新增
        </a-button>
        <a-button
          type="primary"
          :disabled="single"
          @click="$refs.createForm.handleUpdate(undefined, ids)"
        >
          <a-icon type="edit" />修改
        </a-button>
        <a-button type="danger" :disabled="multiple" @click="handleDelete">
          <a-icon type="delete" />删除
        </a-button>
        <a-button type="dashed" @click="$refs.importExcel.importExcelHandleOpen()">
          <a-icon type="import" />导入
        </a-button>
        <a-button type="primary" @click="handleExport">
          <a-icon type="download" />导出
        </a-button>
        <a-button
          type="dashed"
          shape="circle"
          :loading="loading"
          :style="{ float: 'right' }"
          icon="reload"
          @click="getList"
        />
      </div>

      <!-- 增加修改 -->
      <create-form ref="createForm" @ok="getList" />
      <!-- 订单产品 -->
      <product-data ref="productData" @ok="getList" />
      <!-- 上传文件 -->
      <import-excel ref="importExcel" @ok="getList" />

      <!-- 数据展示 -->
      <a-table
        :loading="loading"
        :size="tableSize"
        rowKey="orderId"
        :columns="columns"
        :data-source="list"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :pagination="false"
        :scroll="{ x: 1200 }"
        @change="changeTab"
      >
        <span slot="deliveryTime" slot-scope="text, record">{{ parseTime(record.deliveryTime) }}</span>
        <span slot="createTime" slot-scope="text, record">{{ parseTime(record.createTime) }}</span>
        <span slot="status" slot-scope="text, record">{{ getOrderStatus(record.status) }}</span>
        <span slot="operation" slot-scope="text, record">
          <a
            v-if="record.status === '1' || record.status === '3' || record.status === '5'"
            @click="$refs.createForm.handleUpdate(record, undefined)"
          >
            <a-icon type="edit" />修改
          </a>
          <a-divider
            v-if="record.status === '1' || record.status === '3' || record.status === '5'"
            type="vertical"
          />
          <a @click="handleDelete(record)">
            <a-icon type="delete" />删除
          </a>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link" @click="e => e.preventDefault()">
              <a-icon type="double-right" />操作
            </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="$refs.productData.openData(record)">
                  <a-icon type="check-circle" />产品
                </a>
              </a-menu-item>
              <a-menu-item
                v-if="record.status === '1' || record.status === '3' || record.status === '5'"
              >
                <a @click="changeStatus(record.orderId, '2')">
                  <a-icon type="check-circle" />完成
                </a>
              </a-menu-item>
              <a-menu-item
                v-if="record.status === '1' || record.status === '3' || record.status === '5'"
              >
                <a @click="changeStatus(record.orderId, '4')">
                  <a-icon type="close-circle" />取消
                </a>
              </a-menu-item>
              <a-menu-item v-if="record.status === '2'">
                <a @click="changeStatus(record.orderId, '3')">
                  <a-icon type="close-circle" />返工
                </a>
              </a-menu-item>
              <a-menu-item v-if="record.status === '4'">
                <a @click="changeStatus(record.orderId, '5')">
                  <a-icon type="close-circle" />重启
                </a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>

      <!-- 分页 -->
      <a-pagination
        class="ant-table-pagination"
        show-size-changer
        show-quick-jumper
        :current="queryParam.pageNum"
        :total="total"
        :page-size="queryParam.pageSize"
        :showTotal="total => `共 ${total} 条`"
        @showSizeChange="onShowSizeChange"
        @change="changeSize"
      />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import CreateForm from './modules/CreateForm'
import ProductData from './modules/ProductData'
import CreateDataForm from './modules/CreateDataForm'
import { listOrder, changeStatus, delOrder } from '@/api/erp/order'
import ImportExcel from './modules/ImportExcel'

export default {
  name: 'Order',
  components: {
    CreateForm,
    CreateDataForm,
    ImportExcel,
    ProductData
  },
  data () {
    return {
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        orderCode: undefined,
        customerName: undefined,
        status: undefined,
        username: undefined,
        company: undefined,
        department: undefined,
        params: {}
      },
      total: 0,
      // 高级搜索 展开/关闭
      advanced: false,
      loading: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 订单状态数据字典
      orderStatus: [],
      columns: [
        {
          title: '订单编码',
          dataIndex: 'orderCode',
          width: 100,
          ellipsis: true,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '客户名',
          dataIndex: 'customerName',
          width: 100,
          ellipsis: true,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '公司',
          dataIndex: 'company',
          width: 150,
          ellipsis: true,
          align: 'center'
        },
        {
          title: '部门',
          dataIndex: 'department',
          width: 150,
          ellipsis: true,
          align: 'center'
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: 100,
          ellipsis: true,
          align: 'center',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '总价￥',
          dataIndex: 'totalPrice',
          width: 100,
          ellipsis: true,
          align: 'center'
        },
        {
          title: '送货时间',
          dataIndex: 'deliveryTime',
          width: 200,
          ellipsis: true,
          align: 'center',
          sorter: true,
          scopedSlots: { customRender: 'deliveryTime' },
          sortDirections: ['descend', 'ascend']
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: 200,
          ellipsis: true,
          align: 'center',
          sorter: true,
          scopedSlots: { customRender: 'createTime' },
          sortDirections: ['descend', 'ascend']
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 250,
          scopedSlots: { customRender: 'operation' },
          align: 'center',
          fixed: 'right'
        }
      ],
      list: [],
      selectedRowKeys: [],
      selectedRows: [],
      // 日期范围
      createDateRange: [],
      deliveryDateRange: [],
      ids: [],
      orders: [],
      sort: undefined,
      field: undefined
    }
  },
  created () {
    this.getList()
    this.getDicts('xzg_order_status').then(response => {
      this.orderStatus = response.data
    })
  },
  watch: {
    '$route': {
      handler (route) {
        if (route.name === 'Order') {
          this.queryParam.customerName = route.params.customerName
          this.queryParam.company = route.params.company
          this.queryParam.department = route.params.department
          this.queryParam.customerId = route.params.customerId
          this.queryParam.pageNum = 1
          this.getList()
        }
      }
    }
  },
  methods: {
    handleQuery () {
      this.queryParam.pageNum = 1
      this.getList()
    },
    resetQuery () {
      this.queryParam = {
        pageNum: 1,
        pageSize: 10,
        orderCode: undefined,
        customerName: undefined,
        status: undefined,
        username: undefined,
        company: undefined,
        department: undefined,
        params: {}
      }
      this.deliveryDateRange = []
      this.createDateRange = []
      this.sort = undefined
      this.field = undefined
      this.handleQuery()
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    handleExport () {
      var that = this
      this.$confirm({
        title: '是否确认导出?',
        content: '此操作将导出当前条件下所有数据而非选中数据',
        onOk () {
          that.download('erp/order/export', {
            ...that.queryParam
          }, `order_${new Date().getTime()}.xlsx`)
        },
        onCancel () { }
      })
    },
    getList () {
      this.loading = true
      const dateRangeParam = this.addDateRange(this.queryParam, this.createDateRange, 'create')
      const param = this.addDateRange(dateRangeParam, this.deliveryDateRange, 'delivery')
      if (this.sort !== undefined && this.field !== undefined) {
        param.params['sort'] = this.sort
        param.params['field'] = this.field
      }
      listOrder(param).then(response => {
        this.list = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    handleDelete (row) {
      var that = this
      const orderIds = row.orderId || this.ids
      const orderCodes = row.orderCode || this.codes
      this.$confirm({
        title: '确认删除所选中数据?',
        content: '当前选中编号为' + orderCodes + '的数据',
        onOk () {
          return delOrder(orderIds).then(() => {
            that.onSelectChange([], [])
            that.getList()
            that.$message.success(
              '删除成功',
              3
            )
          })
        },
        onCancel () { }
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.ids = this.selectedRows.map(item => item.orderId)
      this.orders = this.selectedRows.map(item => item.orderCode)
      this.single = selectedRowKeys.length !== 1
      this.multiple = !selectedRowKeys.length
    },
    onShowSizeChange (current, pageSize) {
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    changeSize (current, pageSize) {
      this.queryParam.pageNum = current
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    changeTab (p, f, { field, order }) {
      this.sort = order === 'descend' ? 'desc' : 'asc'
      this.field = field
      this.getList()
    },
    getOrderStatus (status) {
      for (var i = 0; i < this.orderStatus.length; i++) {
        if (this.orderStatus[i].dictValue === status) {
          return this.orderStatus[i].dictLabel
        }
      }
    },
    changeStatus (orderId, status) {
      changeStatus(orderId, status).then(response => {
        this.$message.success(
          '修改成功',
          3
        )
      })
      this.getList()
    }
  }
}
</script>
